package com.echo.code.thread;

import com.echo.code.thread.lock.Lock;
import com.echo.code.thread.lock.helper.ReadWriteLockHelper;
import com.echo.code.thread.lock.helper.impl.ReadWriteLockHelperImpl;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * ShareData Created by baiyap on 2018/9/24.
 */
public class ShareData {

  // default resource char
  private final static char DEFAULT_CHAR = 'c';
  // resource container
  private final List<Character> container = new ArrayList<>();
  private final ReadWriteLockHelper lockHelper = new ReadWriteLockHelperImpl();
  private final Lock readLock = lockHelper.readLock();
  private final Lock writeLock = lockHelper.writeLock();

  public ShareData(int size) {
    IntStream.range(0, size).forEach(i -> container.add(i, DEFAULT_CHAR));
  }

  public static void sleep(int secs) {
    try {
      TimeUnit.SECONDS.sleep(secs);
    } catch (InterruptedException e) {
    }
  }

  public Character[] read() throws InterruptedException {
    readLock.lock();
    try {
      sleep(1);
      return container.toArray(new Character[container.size()]);
    } catch (Exception e) {
      return null;
    } finally {
      readLock.unlock();
    }
  }

  public void write(char c) throws InterruptedException {
    writeLock.lock();
    try {
      System.out.println(Thread.currentThread().getName() + ": " + c);
      sleep(3);
      IntStream.range(0, container.size()).forEach(i -> container.set(i, c));
    } catch (Exception e) {
    } finally {
      writeLock.unlock();
    }
  }
}